package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延时队列中
     *
     * @param id          文章id
     * @param publishTime 发布时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");
        Taskinfo taskinfo = new Taskinfo();
        taskinfo.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        taskinfo.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        taskinfo.setExecuteTime(publishTime);
        byte[] serialize = ProtostuffUtil.serialize(id);
        taskinfo.setParameters(serialize);

        scheduleClient.addTask(taskinfo);

        log.info("添加任务到延迟服务中----end");
    }

    /**
     * 消费延迟队列数据
     */
    @Override
    @Scheduled(fixedRate = 50000)
    public void scanNewsByTask() throws Exception {
        log.info("文章审核---消费任务执行---begin---");
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (responseResult.getCode().equals(200) && responseResult.getData() != null) {
            String toJSONString = JSON.toJSONString(responseResult.getData());
            Taskinfo taskinfo = JSON.parseObject(toJSONString, Taskinfo.class);

            byte[] parameters = taskinfo.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
        log.info("文章审核---消费任务执行---end---");
    }
}
